package com.bcx.wind.workflow.imp.cmd.repositorycmd.windprocesscmd;

import com.bcx.wind.workflow.access.QueryFilter;
import com.bcx.wind.workflow.entity.WindOrder;
import com.bcx.wind.workflow.entity.WindProcess;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.Assert;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.List;

import static com.bcx.wind.workflow.core.constant.ProcessStatus.RECOVERY;
import static com.bcx.wind.workflow.message.ErrorCode.*;

/**
 * 回收流程定义
 *
 * @author zhanglei
 */
public class RecoveryProcessCommand implements Command<Integer> {

    /**
     * 流程定义ID
     */
    private String processId;

    /**
     * 执行数据
     */
    private CommandContext commandContext;


    /**
     * 流程定义
     */
    private WindProcess windProcess;


    public RecoveryProcessCommand(String processId){
        this.processId = processId;
    }

    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return execute();
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }


    private int execute(){
        //查询
        queryProcess();
        //校验状态
        checkProcessStatus();
        //校验是否存在没有执行完的流程实例
        checkOrder();
        //更新状态
        return changeStatus();
    }

    private void checkOrder() {
        QueryFilter filter = new QueryFilter()
                .setProcessId(this.processId);
        List<WindOrder> windOrderList = this.commandContext.access().selectOrderInstanceList(filter);
        Assert.isTrueError(PROCESS_CANNOT_BE_DELETED,!ObjectHelper.isEmpty(windOrderList),this.windProcess.getDisplayName());
    }


    private  int  changeStatus(){
        this.windProcess.setStatus(RECOVERY);
        int ret = this.commandContext.access().updateProcess(windProcess);
        if(ret != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return ret;
    }


    /**
     * 查询
     */
    private  void  queryProcess(){
        this.windProcess = this.commandContext.access().getProcessDefinitionById(this.processId);
        if(this.windProcess == null){
            WindError.error(PROCESS_QUERY_NULL,null,this.processId);
        }
    }

    /**
     * 校验状态是否正确
     */
    private  void checkProcessStatus(){
        String status = this.windProcess.getStatus();
        if(RECOVERY.equals(status)){
            WindError.error(PROCESS_RECOVERY_STATUS_ERROR,null);
        }
    }

}
